import Vue from "vue";
import Router from "vue-router";
import store from "@/store";
import routes from "./routes";
import NProgress from "nprogress"; // 顶部进度条
import "nprogress/nprogress.css"; // 进度条样式
import { getToken } from "@/utils"; // 获取token

NProgress.configure({ showSpinner: false }); // 进度条配置

const whiteList = ["/login"]; // 路由白名单

Vue.use(Router);

const createRouter = () =>
  new Router({
    scrollBehavior: () => ({ y: 0 }),
    routes: routes,
  });

const router = createRouter();

router.beforeEach((to, from, next) => {
  NProgress.start();
  document.title = `非遗文化后台管理系统 - ${to.meta.title}`;
  const token = store.getters.token || getToken();
  if (token) {
    next();
    NProgress.done();
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
export default router;
